import { useMutation } from '@apollo/client';
import { gql } from '@sb/webapp-api-client/graphql';
import { PageHeadline } from '@sb/webapp-core/components/pageHeadline';
import { PageLayout } from '@sb/webapp-core/components/pageLayout';
import { useGenerateLocalePath } from '@sb/webapp-core/hooks';
import { trackEvent } from '@sb/webapp-core/services/analytics';
import { useToast } from '@sb/webapp-core/toast/useToast';
import { FormattedMessage, useIntl } from 'react-intl';
import { useNavigate } from 'react-router';

import { RoutesConfig } from '../../../app/config/routes';
import { {{ pascalCase name }}Form } from '../{{ pascalCase name }}Form/{{ pascalCase name }}Form.component';
import { {{ pascalCase name }}FormFields } from '../{{ pascalCase name }}Form/{{ pascalCase name }}Form.component';
import { ITEMS_PER_PAGE, {{ pascalCase name }}ListQuery } from '../{{ camelCase name }}List/{{ camelCase name }}List.component';

export const add{{ pascalCase name }}Mutation = gql(/* GraphQL */ `
  mutation add{{ pascalCase name }}Mutation($input: Create{{ pascalCase name }}MutationInput!) {
    create{{ pascalCase name }}(input: $input) {
      {{ pascalCase name }}Edge {
        node {
          id
          name
        }
      }
    }
  }
`);

export const Add{{ pascalCase name }} = () => {
  const generateLocalePath = useGenerateLocalePath();
  const { toast } = useToast();
  const intl = useIntl();
  const navigate = useNavigate();

  const successMessage = intl.formatMessage({
    id: '{{ pascalCase name }} form / Success message',
    defaultMessage: '🎉 Item added successfully!',
  });

  const [commit{{ pascalCase name }}FormMutation, { error, loading: loadingMutation }] = useMutation(add{{ pascalCase name }}Mutation, {
    refetchQueries: () => [{
      query: {{ pascalCase name }}ListQuery,
      variables: {
        first: ITEMS_PER_PAGE
      }
    }],
    onCompleted: (data) => {
      const id = data?.create{{ pascalCase name }}?.{{ pascalCase name }}Edge?.node?.id;

      trackEvent('crud', 'add', id);

      toast({ description: successMessage });

      navigate(generateLocalePath(RoutesConfig.{{ camelCase name }}.list));
    },
  });

  const onFormSubmit = (formData: {{ pascalCase name }}FormFields) => {
    commit{{ pascalCase name }}FormMutation({
      variables: {
        input: { name: formData.name },
      },
    });
  };

  return (
    <PageLayout>
      <PageHeadline
        hasBackButton
        header={<FormattedMessage defaultMessage="Add CRUD Example Item" id="Add{{ pascalCase name }} / Header" />}
      />

      <{{ pascalCase name }}Form onSubmit={onFormSubmit} error={error} loading={loadingMutation} />
    </PageLayout>
  );
};